package com.hitqz.robot.dispatch.netty;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.entity.RobotEntity;
import com.hitqz.robot.api.dispatch.model.MessageDto;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xupkun
 * @date 2023/7/17
 */
@Slf4j
public class ChannelCache {


    public static volatile Map<String, ChannelHandlerContext> channelHandlerContextMap =new ConcurrentHashMap<>();

    public static void add(ChannelHandlerContext ctx, String clientId) {
		String ip = ctx.channel().remoteAddress().toString().split(":")[0].substring(1);
        log.warn("[netty]添加通道数据 {}---{}--- {}", ip, clientId, ctx.channel().id());
        channelHandlerContextMap.put(clientId, ctx);
    }

	public static boolean isRegistered(String clientId) {
		return channelHandlerContextMap.containsKey(clientId);
	}



    public static void remove(ChannelHandlerContext ctx) {
		Iterator<Map.Entry<String, ChannelHandlerContext>> iterable = channelHandlerContextMap.entrySet().iterator();
		String clientId= null;
		while (iterable.hasNext()) {
			Map.Entry<String, ChannelHandlerContext> entry = iterable.next();
			ChannelHandlerContext channelHandlerContext  = channelHandlerContextMap.get(entry.getKey());
			if (channelHandlerContext.channel().id() == ctx.channel().id()) {
				clientId = entry.getKey();
				iterable.remove();
				break;
			}
		}

		Cache<Integer, List<RobotEntity>> posInfoDtoCache = SpringUtil.getBean("robotDispatch");
		String finalClientId = clientId;
		// 遍历缓存中的键集合
		for (Integer key : posInfoDtoCache.asMap().keySet()) {
			// 获取对应的机器人实体列表
			List<RobotEntity> robotEntityList = posInfoDtoCache.getIfPresent(key);
			// 如果列表不为空，查找符合条件的 RobotEntity
			if (robotEntityList != null) {
				robotEntityList.stream()
						.filter(robot -> robot.getRobotSn().equals(finalClientId))
						.findFirst()
						.ifPresent(robotEntity -> {
							// 如果找到匹配项，移除并更新缓存
							log.info("移除调度组内缓存信息");
							robotEntityList.remove(robotEntity);
							posInfoDtoCache.put(key, robotEntityList);
						});
				// 一旦找到并更新，即可退出循环
				break;
			}
		}
		log.info("{}离线", clientId);
    }

    //public static ChannelHandlerContext findByChannelId(ChannelId channelId) {
    //    return channelHandlerContextMap.get(channelId);
    //}

	/**
	 * 通过ChannelHandlerContext 获取 ClientId
	 *
	 * @param ctx
	 * @return
	 */
	public static String getClientIdByChannelCtx(ChannelHandlerContext ctx) {
		Map<String, String> kvPair = new HashMap<>();
		channelHandlerContextMap.forEach((clientId, channelCtx) ->
				kvPair.put(channelCtx.channel().id().asLongText(), clientId));
		return kvPair.get(ctx.channel().id().asLongText());
	}

	public static void send2All(MessageDto msg){
		if (CollectionUtil.isNotEmpty(channelHandlerContextMap)) {
			for (String channelId: channelHandlerContextMap.keySet()) {
				ChannelHandlerContext  ctx = channelHandlerContextMap.get(channelId);
				if(ctx != null) {
					msg.setClientId(channelId);
					ctx.channel().writeAndFlush(msg);
					//log.warn("send data to server {}-- {}", ctx.channel().remoteAddress().toString(),
					//		new String(msg.getData(), StandardCharsets.UTF_8));
				}
			}
		}
	}

	public static void send2Client(String clientId, MessageDto msg) {
		ChannelHandlerContext ctx = channelHandlerContextMap.get(clientId);
		if(ctx != null) {
			ctx.channel().writeAndFlush(msg);
		}
	}


}
